package com.xzc.jcip._2_.线程安全性问题;

import net.jcip.annotations.GuardedBy;
import net.jcip.annotations.NotThreadSafe;
import net.jcip.annotations.ThreadSafe;

import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 通过内置锁来让A-THEN-B原子化
 * 但这个性能不好，而且有活跃性问题
 * service方法成为了串行，如果service里面执行时间过长，其它线程就要长时间等待
 * 如果里面有死锁之类的，那就完蛋了
 */
@ThreadSafe
public class SynchronizedFactorizer {
    @GuardedBy("this")
    private final AtomicReference<BigInteger> lastNumber = new AtomicReference<>();
    private final AtomicReference<BigInteger[]> lastFactors = new AtomicReference<>();

    public synchronized BigInteger service(BigInteger num) {
        BigInteger i = num;
        if (i.equals(lastNumber.get())) {
            return i;
        } else {
            BigInteger[] factors = factor(i);
            lastNumber.set(i);
            lastFactors.set(factors);
            return i;
        }
    }

    private synchronized BigInteger[] factor(BigInteger i) {
        return new BigInteger[]{};
    }
}
